//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.example.wechat.login.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@Slf4j
public class HttpUtil {
    private final RestTemplate restTemplate;

    public HttpUtil(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public <T> T get(String url, Class<T> responseType) {
        return (T)this.restTemplate.getForObject(url, responseType, new Object[0]);
    }

    public <T> T get(String url, Map<String, Object> params, Class<T> responseType) {
        ResponseEntity<String> response = this.restTemplate.getForEntity(url, String.class, params);
        String body = response.getBody();
        log.info("response: {}", body);
        try {
            ObjectMapper mapper = new ObjectMapper();
            return (T)mapper.readValue((String)response.getBody(), responseType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to parse response", e);
        }
    }

    public <T> T post(String url, Object request, Class<T> responseType) {
        return (T)this.restTemplate.postForObject(url, request, responseType, new Object[0]);
    }

    public <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpHeaders headers, Object request, Class<T> responseType) {
        HttpEntity<Object> entity = new HttpEntity(request, headers);
        return this.restTemplate.exchange(url, method, entity, responseType, new Object[0]);
    }
}
